package com.netcracker.ui.command;

import com.netcracker.entity.Right;
import com.netcracker.entity.record.BookRecord;
import com.netcracker.util.service.BookService;
import com.netcracker.util.service.ServiceFacade;
import com.netcracker.util.service.exception.DataTransmittingException;
import com.netcracker.util.service.exception.WrongBookException;
import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.LoggerFactory;

public class AddBookCommand implements Command {
    private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(AddBookCommand.class);
    private final ServiceFacade serviceFacade;

    public AddBookCommand(ServiceFacade serviceFacade) {
        this.serviceFacade = serviceFacade;
    }

    @Override
    public String execute(HttpServletRequest request, HttpServletResponse response) {
        Right right = (Right) request.getSession().getAttribute("right");
        if (right != null && (right.equals(Right.USER) || right.equals(Right.ADMIN))) {
            List<Integer> authorIDs = (List<Integer>) request.getAttribute("authorIDs");
            List<Integer> genreIDs = (List<Integer>) request.getAttribute("genreIDs");
            String bookName = request.getParameter("bookName");
            String description = request.getParameter("description");
            Integer edition = Integer.parseInt(request.getParameter("edition"));
            File bookFile = (File) request.getAttribute("bookFile");
            File image = (File) request.getAttribute("image");
            Integer languageID = Integer.parseInt(request.getParameter("languageID"));
            Integer numberOfPages = Integer.parseInt(request.getParameter("numberOfPages"));
            Integer userID = (Integer) request.getSession().getAttribute("id");
            Integer publisherID = Integer.parseInt(request.getParameter("publisherID"));
            String publicDate = request.getParameter("publicDate");
            String bookYear = request.getParameter("year");
        
            SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); 
            SimpleDateFormat formatterYear = new SimpleDateFormat("yyyy");
            Date year = null;
            Date publDate = null;
            try {
                year = formatterYear.parse(bookYear);
                publDate = formatter.parse(publicDate);
            } catch (ParseException ex) {
                LOGGER.error(ex.getMessage(), ex);
            }
            BookService bookService = serviceFacade.getBookService();
            BookRecord bookRecord = new BookRecord();
            bookRecord.setAuthorsIDs(authorIDs);
            bookRecord.setDescription(description);
            bookRecord.setEdition(edition);
            bookRecord.setFile(bookFile);
            bookRecord.setGenreIDs(genreIDs);
            bookRecord.setImage(image);
            bookRecord.setLanguageID(languageID);
            bookRecord.setName(bookName);
            bookRecord.setNumberOfPages(numberOfPages);
            bookRecord.setPublicDate(publDate);
            bookRecord.setPublisherID(publisherID);
            bookRecord.setUserID(userID);
            bookRecord.setYear(year);
            try {
                bookService.addBook(bookRecord);
                request.setAttribute("success", "Книга добавлена.");
                LOGGER.info("Book was added: ", bookName);  
                return "?action=findBook&type=byUser&id="+request.getSession().getAttribute("id");   
            } catch (DataTransmittingException ex) {
                request.setAttribute("error", "Ошибка обращения к БД.");
                LOGGER.error("DB error: ", ex);
                return "index.jsp";
            } catch (WrongBookException ex) {
                request.setAttribute("error", "Заполните все поля.");
                return "?action=newBook";
            }
        } else {
            request.setAttribute("error", "Зарегистрируйтесь или авторизируйтесь для добавления книги.");
            return "registration.jsp";
        }
    }
}
